package com.wangxiaonan.wxwork.config;

import com.wangxiaonan.wxwork.domain.ScheduleJob;
import com.wangxiaonan.wxwork.exeption.ServiceException;
import com.wangxiaonan.wxwork.service.ScheduleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * 定时任务初始化器
 *
 * @Author: wangxiaonan
 * @Date: 2018/8/29
 **/
@Component
public class ScheduleJobInitializer implements ApplicationListener<ContextRefreshedEvent> {
    private static final Logger logger = LoggerFactory.getLogger(ScheduleJobInitializer.class);

    @Resource
    private ScheduleService scheduleService;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        logger.info("---------------- start init schedule job ----------------");
        try {
            scheduleService.clearJob();
        } catch (ServiceException e) {
            logger.error("[ScheduleJobInitializer] onApplicationEvent >>> scheduler.clear() 初始化失败", e);
            return;
        }

        List<ScheduleJob> scheduleJobs = scheduleService.getScheduleJobsWithBLOBs(new ScheduleJob());
        if (CollectionUtils.isEmpty(scheduleJobs)) {
            return;
        }
        for (ScheduleJob job : scheduleJobs) {
            try {
                scheduleService.scheduleJob(job);
            } catch (ServiceException e) {
                logger.error("[ScheduleJobInitializer] >>> scheduler.scheduleJob 定时任务启动失败 >>> {}", job.getId());
                continue;
            }
        }
    }
}
